package com.scs.application.modules.wm.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.consts.GlobalConsts;
import com.scs.application.core.query.QueryContext;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.dept.entity.Use;
import com.scs.application.modules.dept.entity.UseDtl;
import com.scs.application.modules.dept.mapper.UseDtlMapper;
import com.scs.application.modules.dept.mapper.UseMapper;
import com.scs.application.modules.sys.model.PageResult;
import com.scs.application.modules.wm.dto.DailyOrderItemDTO;
import com.scs.application.modules.wm.dto.StockDTO;
import com.scs.application.modules.wm.dto.WorkOrderItemDTO;
import com.scs.application.modules.wm.entity.Stock;
import com.scs.application.modules.wm.entity.WorkOrderItem;
import com.scs.application.modules.wm.mapper.StockMapper;
import com.scs.application.modules.wm.mapper.WorkOrderItemMapper;
import com.scs.application.modules.wm.service.StockService;
import com.scs.application.modules.wm.service.WorkOrderItemService;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 入库单明细 服务实现类
 * </p>
 */
@Service
public class WorkOrderItemServiceImpl extends BaseServiceImpl<WorkOrderItemMapper, WorkOrderItem> implements WorkOrderItemService {
    @Autowired
    private UseDtlMapper useDtlMapper;
    @Autowired
    private UseMapper useMapper;
    @Autowired
    private StockService stockService;

    @Autowired
    private StockMapper stockMapper;

    @Override
    public List<WorkOrderItemDTO> workOrderItemBySN(String sn) {
        List<WorkOrderItemDTO> workOrderItems = this.baseMapper.workOrderItemBySN(sn);
        return workOrderItems;
    }

    @Override
    public List<WorkOrderItemDTO> orderBarcodeBySN(String sn) {
        List<WorkOrderItemDTO> orderBarcodes = this.baseMapper.orderBarcodeBySN(sn);
        return orderBarcodes;
    }

    @Override
    public List<DailyOrderItemDTO> workOrderItemOmoc(List<String> ids) {
        List<DailyOrderItemDTO> workOrderItems = this.baseMapper.workOrderItemOmoc(ids);
        return workOrderItems;
    }

    @Override
    public PageResult pageForRedType(QueryContext queryContext) {
        // 获取当前科室下，符合 定数包条件/高耗条件 的sn列表
        List<StockDTO> stockList = stockService.dtoList(queryContext.getWrapper());
        List<String> stockSns = Lists.newArrayList();
        if (!stockList.isEmpty()) {
            stockSns = stockList.stream().map(o -> o.getSn()).collect(Collectors.toList());
        }
        // 已经存在冲红的sn列表
        List<Use> redTypeList = useMapper.selectList(Wrappers.<Use>query()
                .eq("flag_use_red_type", GlobalConsts.YES)
        );
        List<String> existSns = Lists.newArrayList();
        if (!redTypeList.isEmpty()) {
            List<UseDtl> useDtls = useDtlMapper.selectList(Wrappers.<UseDtl>query()
                    .in("use_id", redTypeList.stream().map(o -> o.getId()).collect(Collectors.toList())));
            if (!useDtls.isEmpty()) {
                existSns = useDtls.stream().map(o -> o.getSnNo()).collect(Collectors.toList());
            }
        }

        IPage page = this.page(queryContext.getPage(), Wrappers.<WorkOrderItem>query()
                .in(!stockSns.isEmpty(), "sn", stockSns)
                .notIn(!existSns.isEmpty(), "sn", existSns)
        );
        List<WorkOrderItem> workOrderItemList = page.getRecords();
        List<WorkOrderItemDTO> dtoList = Lists.newArrayListWithCapacity(workOrderItemList.size());
        workOrderItemList.forEach(workOrderItem -> {
            WorkOrderItemDTO workOrderItemDTO = new WorkOrderItemDTO();
            BeanUtils.copyProperties(workOrderItem,workOrderItemDTO);
            dtoList.add(workOrderItemDTO);
        });
        Map<String, List<WorkOrderItemDTO>> map = dtoList.stream().filter(o -> StringUtils.isNotBlank(o.getSn())).collect(Collectors.groupingBy(WorkOrderItem::getSn));

        List<WorkOrderItemDTO> list = Lists.newArrayList();
        for (String sn : map.keySet()) {
            List<WorkOrderItemDTO> items = map.get(sn);
            if (items.size() == 1) {
                list.addAll(items);
            }
        }
        // 设置是否一物一码，是否寄售
        if (!stockList.isEmpty()) {
            Map<String, Stock> stockMap = stockList.stream().collect(Collectors.toMap(o -> o.getSn(), o -> o, (o1, o2) -> o1));
            list.stream().forEach(o -> {
                o.setFlagConsignment(stockMap.get(o.getSn()).getFlagConsignment());
                o.setFlagOmoc(stockMap.get(o.getSn()).getFlagOmoc());
            });
        }

        return PageResult.ok("success", list, list.size());
    }

    @Override
    public List<Stock> selectOprtBag() {
        return stockService.list(Wrappers.<Stock>query()
                .eq("matr_type", "1")
                .gt("sku_qty", 0)
                .notInSql("id", "select ifnull(stock_id,'') from wm_stock_lock"));
    }

    @Override
    public List<WorkOrderItemDTO> getListByMatrId(String matrId) {
        List<WorkOrderItemDTO> workOrderItemDTOS = this.baseMapper.workOrderItemByMatrId(matrId);
        return workOrderItemDTOS;
    }

    @Override
    public double getOutspItemSkuQtySum(List<String> stockIds, Boolean flagOmoc) {
        double sumQty = this.baseMapper.getOutspItemSkuQtySum(stockIds, flagOmoc);
        return sumQty;
    }

    @Override
    public Double getSumSkuQty(String startDate, String endDate) {
        return this.baseMapper.getSumSkuQty(startDate, endDate);
}

    @Override
    public Double getSumAmount(String startDate, String endDate) {
        return this.baseMapper.getSumAmount(startDate, endDate);
    }
}
